﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Skugo.Shared;
using System.IO;

namespace Skugo
{
    public class ConsoleInput : EventArgs
    {
        public String Text;
    }

    public class Console : DockablePlugin
    {
        /// <summary>
        /// The type of message we send or receieve.
        /// </summary>
        enum MessageType : byte
        {
            WriteMessage,
            UserInput,
        }

        /// <summary>
        /// The name of the remote type we wish to instantiate.
        /// </summary>
        private const String RemoteType = "Skugo.StandardPlugins.Console";

        public event EventHandler<ConsoleInput> OnConsoleInput;


        public Console(Client client, String displayName) :
            base(RemoteType, client, displayName)
        {
        }

        public void Write(String text)
        {
            // Create a memory stream to write data to
            MemoryStream stream = new MemoryStream();

            // Create a binary writer to write the data
            BinaryWriter outgoing = new BinaryWriter(stream);

            outgoing.Write((Byte)MessageType.WriteMessage);
            outgoing.WriteAsciiString(text);

            this.Send(stream.ToArray());
        }

        public void WriteLine(String text)
        {
            this.Write(text + "\n");
        }

        protected override void OnReceive(byte[] data)
        {
            var stream = new MemoryStream(data);

            var incoming = new BinaryReader(stream);

            var message = (MessageType)incoming.ReadByte();

            switch (message)
            {
                case MessageType.UserInput:
                {
                    var text = incoming.ReadAsciiString();

                    if (this.OnConsoleInput != null)
                    {
                        var e = new ConsoleInput();
                        e.Text = text;
                        this.OnConsoleInput(this, e);
                    }
                    break;
                }
            }
        }
    }
}
